<template>
  <div>
    <div class="row-header">
      <el-form ref="form" :model="form" label-width="100px" :inline="$store.state.app.screenWidth<992?false:true">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item label="是否返佣" prop="rebate">
          <el-select v-model="form.rebate">
            <el-option value="C_YES" label="是"></el-option>
            <el-option value="C_NO" label="否"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="套餐大类" prop="mealOne">
          <el-select v-model="form.mealOne" @change="changeMealOne(1,$event)">
            <el-option v-for="item in mealOneOptions" :label="item.label" :value="item.value" :key="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="套餐小类" prop="mealTwo">
          <el-select v-model="form.mealTwo">
            <el-option v-for="item in mealTwoOptions" :label="item.label" :value="item.value" :key="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="到期时间" prop="time">
          <el-date-picker
            v-model="form.time"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="创建时间" prop="date">
          <el-date-picker
            v-model="form.date"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div class="row-form-btn">
        <el-button type="shenda" size="small" icon="el-icon-search" @click="searchForm('form')">查询</el-button>
        <el-button type="shenda" size="small" icon="el-icon-refresh-right" @click="resetForm('form')">重置</el-button>
      </div>
    </div>
    <div class="split-line"></div>
    <div class="row-main">
      <el-button type="shenda" size="small" icon="el-icon-refresh" @click="current=1,initData()">刷新数据</el-button>
      <el-button type="shenda" size="small" icon="el-icon-plus" @click="addRecord">新增卡密</el-button>
      <router-link to="exchangeFlowList">
        <el-button type="shenda" size="small" icon="el-icon-s-order" style="margin-left: 10px">查看全部卡密</el-button>
      </router-link>
      <el-table :header-cell-style="{ 'background':$store.state.app.tableBgColor,'color':'#606266' }"
                :data="tableData" class="row-main-table"
                ref="table" tooltip-effect="dark"
                v-loading.fullscreen="tableLoading" element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.2)">
        <el-table-column prop="recordName" label="名称" align="center" :width="$store.state.app.screenWidth<992?'130px':'auto'" :fixed="$store.state.app.screenWidth<992?true:false"></el-table-column>
        <el-table-column prop="setMealHeadName" label="套餐大类" align="center" :width="$store.state.app.screenWidth<992?'150px':'auto'"></el-table-column>
        <el-table-column prop="setMealName" label="套餐小类" align="center" :width="$store.state.app.screenWidth<992?'150px':'auto'"></el-table-column>
        <el-table-column prop="dictIsRakeBack" label="是否开启返佣" align="center" :width="$store.state.app.screenWidth<992?'150px':'auto'">
          <template slot-scope="scope">
            <span v-if="scope.row.dictIsRakeBack=='C_YES'">是</span>
            <span v-if="scope.row.dictIsRakeBack=='C_NO'">否</span>
            <span v-if="scope.row.dictIsRakeBack==''">--</span>
          </template>
        </el-table-column>
        <el-table-column prop="allCount" label="生成卡密数量" align="center" :width="$store.state.app.screenWidth<992?'150px':'auto'"></el-table-column>
        <el-table-column prop="endTimeDate" label="到期时间" align="center" :width="$store.state.app.screenWidth<992?'150px':'auto'"></el-table-column>
        <el-table-column prop="employeeName" label="操作人姓名" align="center" :width="$store.state.app.screenWidth<992?'150px':'auto'"></el-table-column>
        <el-table-column label="操作" align="center" :width="$store.state.app.screenWidth<992?'150px':'auto'">
          <template slot-scope="scope">
            <el-dropdown trigger="click">
              <div>
                <svg-icon class="el-dropdown-link" icon-class="operation"></svg-icon>
              </div>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>
                  <router-link :to="{path: '/exchangeFlow/exchangeFlowList', query:{id: scope.row.id,name: scope.row.recordName}}">
                    <el-button class="operation" style="width: 100%;">查看全部卡密</el-button>
                  </router-link>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button class="operation" @click="switchFlag(scope.row)">废弃/启用所有卡密</el-button>
                </el-dropdown-item>
              </el-dropdown-menu>
              <el-dropdown-menu slot="dropdown">

              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <div :style="{'overflow':$store.state.app.screenWidth<992?'scroll':'auto'}">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="row-main-pager"
          :current-page.sync="current"
          :page-size="pageSize"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          background></el-pagination>
      </div>
    </div>
    <!--  新增卡密弹窗  -->
    <el-dialog title="新增卡密" :top="$store.state.app.screenWidth<600?'10vh':'33vh'" :visible.sync="addRecordDialog" :width="$store.state.app.screenWidth<600?'100%':'600px'" center>
      <el-form label-width="120px" :model="addForm" ref="addForm" :rules="addRules" :label-position="$store.state.app.screenWidth<500?'top':'right'">
        <el-form-item label="卡密名称" prop="title">
          <el-input v-model="addForm.title" placeholder="请输入卡密名称"/>
        </el-form-item>
        <el-form-item label="套餐大类" prop="mealOne">
          <el-select v-model="addForm.mealOne" @change="changeMealOne(2,$event)">
            <el-option v-for="item in mealOneOptions" :label="item.label" :value="item.value" :key="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="套餐小类" prop="mealTwo" v-if="addForm.mealOne">
          <el-select v-model="addForm.mealTwo">
            <el-option v-for="item in mealTwoOptions" :label="item.label" :value="item.value" :key="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否开启返佣" prop="open">
          <el-radio-group v-model="addForm.open">
            <el-radio label="C_YES">是</el-radio>
            <el-radio label="C_NO">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="生成卡密个数" prop="num">
          <el-input v-model="addForm.num"/>
        </el-form-item>
        <el-form-item label="卡密到期时间" prop="time">
          <el-date-picker
            v-model="addForm.time"
            type="date"
            placeholder="选择日期"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <span class="dialog-footer" slot="footer">
      <el-button @click="addRecordDialog = false" size="small">取 消</el-button>
      <el-button type="primary" size="small" v-preventReClick @click="onSubmit('addForm')">确 定</el-button></span>
    </el-dialog>
    <!--  启用 or 废弃卡密  -->
    <el-dialog title="启用/废弃卡密" top="33vh" :visible.sync="editeRecordDialog" :width="$store.state.app.screenWidth<600?'100%':'600px'" center>
      <el-form :model="editeForm" ref="editeForm" >
        <el-form-item label="启用或废弃卡密" prop="flag">
          <el-radio-group v-model="editeForm.status" @change="changeFlag">
            <el-radio-button label="C_YES">废弃</el-radio-button>
            <el-radio-button label="C_NO">启用</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span class="dialog-footer" slot="footer">
        <el-button @click="editeRecordDialog = false" size="small">取 消</el-button>
        <el-button type="primary" size="small" v-preventReClick @click="update" :loading="loading">确 定</el-button></span>
    </el-dialog>
  </div>
</template>

<script>
import {
  packageCatListForMonth,
  getSetMealList,
  exchangeFlowList,
  addExchangeFlowRecord,
  exchangeFlowEdite,
  exchangeFlowSearch,
} from '@/api/getData'

export default {
  name: "",
  data() {
    return {
      current: 1,
      pageSize: 10,
      total: 0,
      tableData: [],
      tableLoading: false,
      addRecordDialog: false,
      editeRecordDialog: false,
      form: {
        name: '',
        rebate: '',
        mealOne: '',
        mealTwo: '',
        time: '',
        date: '',
      },
      addForm: {
        title: '',
        mealOne: '',
        mealTwo: '',
        open: '',
        num: '',
        time: '',
      },
      addRules: {
        title: [
          {required: true, message: '请填写卡密名称'}
        ],
        mealOne: [
          {required: true, message: '请选择套餐大类', trigger: 'change'}
        ],
        mealTwo: [
          {required: true, message: '请选择套餐小类', trigger: 'change'}
        ],
        open: [
          {required: true, message: '请选择是否开启返佣', trigger: 'change'}
        ],
        num: [
          {required: true, message: '请填写生成卡密个数'},
          {pattern: /^[1-9]\d*/, message: '当前位置只能输入正整数'}
        ],
        time: [
          {required: true, message: '请选择卡密有效期', trigger: 'change'},
          {
            validator: ((rule, value, callback) => {
              let d = new Date();
              let dd = d.getTime();
              let tt = new Date(value).getTime();
              if (dd > tt) {
                callback("卡密到期时间不能早于当前时间")
              } else {
                callback()
              }
            }), trigger: 'change'
          }
        ],
      },
      mealOneOptions: [],
      mealTwoOptions: [],
      editeForm: {
        status: '',
        headId: '',
      },
      loading: false,
    }
  },
  mounted() {
    this.initData();
    this.getMealOneOptions();
  },
  methods: {
    changeFlag(row) {
      let tip = this.editeForm.status=='C_YES'?'废弃':'启用';
      exchangeFlowSearch({
        headId: this.editeForm.headId,
        dictIsUnable: this.editeForm.status,
      }).then(res => {
        if (res.code == 10000) {
          if(res.data==0){
            this.$alert(`当前暂无可执行${tip}的数据，点击确定关闭弹窗`, '提示', {
              confirmButtonText: '确定',
              callback: action => {
                this.editeRecordDialog = false;
              }
            });
          }
          else{
            this.$confirm(`是否对当前${res.data}条数据继续执行${tip}卡密?`, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.loading = true;
              this.update()
            }).catch(() => {

            });
          }
        }
      })
    },
    switchFlag(row){
      this.editeForm.headId = row.id;
      this.editeRecordDialog = true;
    },
    searchForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.initData();
        }
      })
    },
    onSubmit(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          let returnData = await addExchangeFlowRecord({
            setMealHeadId: this.addForm.mealOne,
            setMealId: this.addForm.mealTwo,
            recordName: this.addForm.title,
            dictIsRakeBack: this.addForm.open,
            allCount: this.addForm.num,
            endTime: this.addForm.time
          })

          this.addRecordDialog = false;
          this.initData();
        }
      })
    },
    async initData() {
      this.tableLoading = true;
      let time1 = '';
      let time2 = '';
      let date1 = '';
      let date2 = '';
      if (this.form.time.length > 0) {
        time1 = this.form.time[0];
        time2 = this.form.time[1];
      }
      if (this.form.date.length > 0) {
        date1 = this.form.date[0];
        date2 = this.form.date[1];
      }
      let returnData = await exchangeFlowList({
        setMealHeadId: this.form.mealOne,
        setMealId: this.form.mealTwo,
        recordName: this.form.name,
        dictIsRakeBack: this.form.rebate,
        beginEndTime: time1,
        endEndTime: time2,
        beginInsertTime: date1,
        endInsertTime: date2,
        page: {
          current: this.current.toString(),
          size: this.pageSize.toString()
        }
      });
      this.tableData = [];
      this.total = 0;
      if (returnData.code == 10000) {
        returnData.data.records.map(item => {
          this.tableData.push(item);
        })
        this.total = returnData.data.total;
      }
      this.tableLoading = false;
    },
    addRecord() {
      this.addRecordDialog = true;
      this.$nextTick(() => {
        this.$refs['addForm'].resetFields();
      })
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.current = 1;
      this.initData();
    },
    handleCurrentChange(val) {
      this.current = val;
      this.initData();
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.mealTwoOptions = [{value:'',label:'请选择'}]
    },
    async changeMealOne(n, val) {
      if (n == 1) {
        this.form.mealOne = val;
        this.form.mealTwo = '';
      } else {
        this.addForm.mealOne = val;
        this.addForm.mealTwo = '';
      }

      this.mealTwoOptions = [{value: '', label: '请选择'}];
      if(val){
        let returnData = await getSetMealList({
            headId: val,
            mealName: '',
            page: {
              current: '1',
              size: '99999',
              ascs: [],
              descs: []
            }
          },
          {
            obj: this,
            key: 'tableLoading'
          });
        if (returnData._result) {
          returnData.data.records.map(item => {
            let obj = {};
            obj.value = item.id;
            obj.label = item.mealName;
            this.mealTwoOptions.push(obj)
          })
        }
      }

    },
    async getMealOneOptions() {
      this.mealOneOptions = [{value: '', label: '请选择'}];
      const returnData = await packageCatListForMonth({
          page: {
            current: '1',
            size: '9999',
            ascs: [],
            descs: []
          }
        },
        {
          obj: this,
          key: 'tableLoading'
        })
      if (returnData._result) {
        returnData.data.records.map(item => {
          let obj = {};
          obj.value = item.id;
          obj.label = item.name;
          this.mealOneOptions.push(obj);
        })
      }
    },
    update() {
      if(!this.editeForm.status){
        this.$message.error('请选择卡密是否废弃')
        return false
      }
      exchangeFlowEdite({
        headId: this.editeForm.headId,
        dictIsUnableForActive: this.editeForm.status
      }).then(res => {
        this.editeRecordDialog = false;
        this.loading = false;
        let text = res.data == 0 ? '所有数据操作成功' : '当前' + res.data + '失败条数据'
        this.$alert(text, '提示', {
          confirmButtonText: '确定',
          callback: action => {
            this.editeRecordDialog = false;
            this.editeForm.status = '';
          }
        });
      })
    }
  }
}
</script>

<style scoped>

</style>
